#include "clientsocket.h"

#include <QDataStream>

class ClientSocket::ClientSocketPrivate {
public:
	ClientSocketPrivate();

	quint32 m_toRecive;

	bool m_authorized;
	quint64 m_userId;
};

ClientSocket::ClientSocketPrivate::ClientSocketPrivate(){
	m_toRecive = 0;
	m_userId = 0;
	m_authorized = false;
}

//end of d-class
//------------------------------------------------------------------------------
ClientSocket::ClientSocket(QObject *parent) :
	QSslSocket(parent),
	d(new ClientSocketPrivate())
{
	connect(this, SIGNAL(readyRead()), this, SLOT(readPartOfData()) );
}

ClientSocket::~ClientSocket(){
	delete d;
}

bool ClientSocket::isAuthorized() const {
	return d->m_authorized;
}

void ClientSocket::setAutorized(bool flag){
	d->m_authorized = flag;
}

void ClientSocket::setUserId(quint64 id){
	d->m_userId = id;
}

quint64 ClientSocket::userId() const {
	return d->m_userId;
}

void ClientSocket::readPartOfData(){
	QDataStream in( this );
	in.setVersion( QDataStream::Qt_4_7 );

	if( d->m_toRecive == 0 ){
		if( bytesAvailable() < static_cast<int>(sizeof(quint32)) )
			return;
		in >> d->m_toRecive;
	}

	if( bytesAvailable() < d->m_toRecive )
		return;

	QByteArray data = readAll();

	emit dataReaded( this, data );
	d->m_toRecive = 0;

	//todo
	//check if ther is more data to read it's probably next command
}

